package com.link.base.wechat.authweb.util;

import com.alibaba.fastjson.JSONObject;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.HttpRequestUtil;
import com.link.core.util.StringUtils;

/**
 * 微信网页授权工具类
 * 
 * @author ouyangzhenqiang
 * @date 2019/03/11 01:50
 */
public class WxAuthWebUtil {
    
    /**
     * 开发者模式下，基于code获取用户openId/unionId/access_token
     * 
     * @author ouyangzhenqiang
     * @date 2019/03/11 01:51
     * @param code code
     * @param wxAppId 微信公众号应用Id
     * @param wxAppSecret 微信公众号应用secret
     */
    public static JSONObject getUserInfoByDevCode(String code, String wxAppId, String wxAppSecret) throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("AUTHWEB-005");
        }
        if (StringUtils.isBlank(wxAppId)) {
            throw new ServiceException("AUTHWEB-002");
        }
        if (StringUtils.isBlank(wxAppSecret)) {
            throw new ServiceException("AUTHWEB-006");
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=" + wxAppId + "&secret=" + wxAppSecret + "&code=" + code + "&grant_type=authorization_code";
        String resultStr = HttpRequestUtil.sendGet(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 第三方平台模式下，基于code获取用户openId/unionId/access_token
     *
     * @author ouyangzhenqiang
     * @date 2019/03/11 01:51
     * @param code code
     * @param wxAppId 微信公众号应用Id
     * @param componentAppId 第三方平台应用Id
     * @param componentAccessToken 第三方平台接口调用凭证
     */
    public static JSONObject getUserInfoByComponentCode(String code, String wxAppId,
                                                        String componentAppId, String componentAccessToken) throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("AUTHWEB-005");
        }
        if (StringUtils.isBlank(wxAppId)) {
            throw new ServiceException("AUTHWEB-002");
        }
        if (StringUtils.isBlank(componentAppId)) {
            throw new ServiceException("AUTHWEB-007");
        }
        if (StringUtils.isBlank(componentAccessToken)) {
            throw new ServiceException("AUTHWEB-008");
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/component/access_token";
        String param = "appid=" + wxAppId + "&code=" + code + "&grant_type=authorization_code"
            + "&component_appid=" + componentAppId + "&component_access_token=" + componentAccessToken;
        String resultStr = HttpRequestUtil.sendGet(url, param);
        return WxExceptionUtil.parse(resultStr);
    }
}
